package cn.yeyiu.mangaviewer;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import cn.yeyiu.util.bean.MangaEP;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.List;


public class MangaViewActivity extends AppCompatActivity {
    private TextView curPageTv;
    private TextView sumPageTv;
    private TextView epTitleTv;

    private RecyclerView recyclerView;
    private MangaViewAdapter adapter;
    private MangaEP mangaEP;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_manga_view);

        initData();
        bindView();
        bindEvent();
        bindAdapter();
        initUI();
    }

    void bindView() {
        this.recyclerView = (RecyclerView) findViewById(R.id.manga_rv);
        this.curPageTv = (TextView) findViewById(R.id.manga_cur_page_tv);
        this.sumPageTv = (TextView) findViewById(R.id.manga_sum_page_tv);
        this.epTitleTv = (TextView) findViewById(R.id.manga_ep_tv);
    }

    void bindAdapter() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        this.recyclerView.setLayoutManager(linearLayoutManager);
        this.recyclerView.setAdapter(this.adapter);
    }

    private void bindEvent() {
        this.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int i) {
                super.onScrollStateChanged(recyclerView, i);
                MangaViewActivity.this.curPageTv.setText(
                        String.valueOf(((LinearLayoutManager) recyclerView.getLayoutManager())
                                .findLastVisibleItemPosition() + 1));
            }
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int i, int i2) {
                super.onScrolled(recyclerView, i, i2);
            }
        });
    }

    private void initData() {
        this.mangaEP = JSONObject.parseObject(getIntent().getStringExtra("mangaEP"), MangaEP.class);
        this.adapter = new MangaViewAdapter(this, this.mangaEP);
    }

    private void initUI(){
        String title = this.mangaEP.getTitle();
        title=title.substring(Math.max(title.length() - 6, 0));
        this.epTitleTv.setText(title);
        this.sumPageTv.setText(String.valueOf(this.mangaEP.picList.size()));
    }
}
